package 滑动窗口;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: biubiu0002
 * @Date: 2021-09-14 11:04
 **/
public class 最小覆盖子串 {
    public static void main(String[] args) {

    }

    public String minWindow(String s, String t) {
        Map<Character, Integer> window = new HashMap();
        Map<Character, Integer> need = new HashMap();
        for (int i = 0; i < t.length(); i++) {
            Character c = t.charAt(i);
            need.put(c, need.getOrDefault(c, 0) + 1);
            // System.out.println(c);
        }
        // System.out.println("need需求："+need);
        int left = 0, right = 0;
        int valid = 0;//valid 表示窗口中满足need条件的字符个数，若valid==need.size()  区间[left,right)
        //子串的起始索引与长度
        int start = 0, len = Integer.MAX_VALUE;
        while (right < s.length()) {
            //开始滑动
            Character c = s.charAt(right);
            //右移窗口
            right++;
            //窗口数据更新
            if (need.containsKey(c)) {
                // System.out.println("含有要求字符："+c);
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (need.get(c).equals(window.get(c))) {
                    //到达要求
                    // System.out.println("到达要求");
                    valid++;
                }
            }
            //判断左窗口是否要收缩
            while (valid == need.size()) {
                //在这里更新覆盖最小子串
                if (right - left < len) {
                    start = left;
                    len = right - left;
                    // System.out.println(s.substring(left) );
                }
                // d 是要移出窗口的字符
                char d = s.charAt(left);
                //窗口收缩
                left++;
                if (need.containsKey(d)) {

                    if (window.get(d).equals(need.get(d))) {
                        valid--;
                    }
                    window.put(d, window.get(d) - 1);

                }


            }

        }
        return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);

        // return "hello";


    }
}
